import {Utils, WebStorage} from "jboot-env";
import Encrypt from "./encrypt";
const keyMapping = {};

export default function (config, options){
	config.api(require.context('./api/', true, /\.js/))
		.baseUrl('/__api/')
		.appendPage2Url()
		.loading(false)
		.headers({
			'token': function () {
				return WebStorage.localMode().get('{PROJECT_NAME}-token');
			},
		})
		.before(function (config) {
			if(config.encrypt && ['request', 'response'].includes(config.encrypt)){
				let data = config.data, random;

				// 生产随机密码
				random = Encrypt.getRandom(8);

				let encryptKey = Encrypt.rsaEncrypt('公共秘钥', random);

				// 密码RSA加密
				config.headers['a-k-l-t'] = encryptKey;

				keyMapping[encryptKey] = random;

				if(data) config.data = Encrypt.tripleDESEncrypt(random, JSON.stringify(data));
			}
		})
		.after(function (response) {
			if(response.config.encrypt && response.config.encrypt === 'response'){
				let encryptKey = response.config.headers['a-k-l-t'],
					key = keyMapping[encryptKey];

				delete keyMapping[encryptKey];

				let responseData = response.data;

				if (key && responseData.success === true) {
					if (responseData.data) {
						let decryptResponse = Encrypt.tripleDESDecrypt(key, responseData.data);

						try {
							decryptResponse = JSON.parse(decryptResponse);
						} catch (e) {
						}

						responseData = Object.assign({}, responseData, {
							data: decryptResponse
						})
					} else {
						responseData = Encrypt.tripleDESDecrypt(key, responseData);
					}

					response.data = responseData;
				}
			}
		})
		.error(error => new Promise((resolve, reject) => {
			let {vue} = options.getInstance(),
				responseInfo = Utils.blank2Default(error.response, {}),
				responseData = Utils.blank2Default(responseInfo.data, {});
			if (responseData.code === 401) {
				vue.$jump({name: 'auth'}, true);
			} else {
				reject(error);
			}
		}));
}
